package cn.mill.core.modem;

import java.lang.reflect.Type;
import java.text.ParseException;
import java.util.Date;

import cn.mill.common.Context;
import cn.mill.common.annotation.Property;
import cn.mill.common.data.Item;

public class DateSpell implements FieldSpell {
	
	public static final DateSpell INSTANCE = new DateSpell();
	
	@Override
	public Item resolver(Context context, String name, Type type, Object object) {
		Item item = new Item();
		item.setName(name);
		item.setType(type);
		item.setValue(object);
		return item;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public <T> T builder(Type type, Item item) {
		Property property = item.getProperty();
		java.text.DateFormat format = new java.text.SimpleDateFormat((property.format() == null ? "yyyy-MM-dd hh:mm:ss" : property.format()));
		Date d = null;
		try {
			d = format.parse((String) item.getValue());
		} catch (ParseException e) {
			d = new Date(0);
		}
		return (T) d;
	}
	
}
